import React,{Component} from "react";
import './Task.css';

class Task extends Component {
    constructor(props) {
        super(props);
        this.state = {
            array : [
                {name:'编程任务',bol:false,edit:false},
                {name:'编程React任务',bol:false,edit:false},
                {name:'编程ES6任务',bol:false,edit:false}
            ]
        };
        this.textInput = React.createRef();
        this.handleClick = this.handleClick.bind(this);
    }

    handleChange(index){
        let array = this.state.array;
        array[index].bol = !array[index].bol;
        this.setState({
            array : array
        });
    }

    handleClick(){
        let value = this.textInput.current.value;
        let array = this.state.array;
        array.push({
            name : value,
            bol : false,
            edit : false
        });
        this.setState({
            array : array
        });
        this.textInput.current.value = '';
    }

    handleClick2(index){
        let array = this.state.array;
        array[index].edit = !array[index].edit;
        this.setState({
            array : array
        });
    }

    handleChange2(index,e){
        let name = e.target.value;
        let array = this.state.array;
        array[index].name = name;
        this.setState({
            array : array
        });
    }

    render() {
        let num = 0;
        this.state.array.forEach((item)=>{
            if (!item.bol) {
                num++;
            }
        });
        return (
            <div>
                总任务：{this.state.array.length}；未完成：{num}；【完成】
                <br />
                <ul>
                    {
                        this.state.array.map((item,index)=>{
                            return <li key={index} className={item.bol?'aaa':''}>
                                <input type="checkbox" checked={item.bol} onChange={this.handleChange.bind(this,index)}/>
                                <span className={!item.edit?'d_i':'d_n'} onClick={this.handleClick2.bind(this,index)}>{item.name}</span>
                                <input type="text" className={item.edit?'d_i':'d_n'} value={item.name}
                                       onChange={this.handleChange2.bind(this,index)}
                                       onBlur={this.handleClick2.bind(this,index)}/>
                            </li>;
                        })
                    }
                </ul>
                <input type="text" ref={this.textInput}/>
                <input type="button" value="添加" onClick={this.handleClick}/>
            </div>
        );
    }
}

export default Task;